#!/bin/bash
#
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0

set -euo pipefail

excluded=(
    "/integration"
    "/ldap"
)

# join array elements by the specified string
join_by() {
    local IFS="$1"; shift
    [ "$#" -eq 0 ] && return 0
    echo "$*"
}

list_and_filter() {
    local filter
    filter=$(join_by '|' "${excluded[@]}")
    if [ -n "$filter" ]; then
        go list "$@" 2>/dev/null | grep -Ev "${filter}" || true
    else
        go list "$@" 2>/dev/null
    fi
}

run_tests() {
    GO_TAGS=${GO_TAGS:-}
    [ -n "$GO_TAGS" ] && echo "Testing with $GO_TAGS..."

    time go test -tags "$GO_TAGS" -cover -timeout 15m -p 1 "$@"
}

main() {
    local packages=()
    while IFS= read -r pkg; do
        packages+=("$pkg");
    done < <(list_and_filter "github.com/hyperledger/fabric-ca/...")

    run_tests "${packages[@]}"
    GO_TAGS="pkcs11" run_tests "${packages[@]}"
}

main
